package com.cmhi.base.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.IdRes;

import com.cmhi.base.action.HandlerAction;
import com.cmhi.base.view.SettingDevInfoLayout;
import com.cmhi.base.action.ClickAction;
import com.cmhi.base.R;
import com.cmhi.base.entity.AppInfo;
import com.cmhi.base.provider.BimDataManager;
import com.cmhi.base.utils.BimTools;
import com.cmhi.base.utils.BitmapUtil;
import com.softmbh.kellyplatform.util.AppUtils;
import com.softmbh.kellyplatform.util.CheckerUtils;
import com.softmbh.kellyplatform.util.MacUtils;
import com.yxl.yxlbus.YxlBusManager;
import com.yxl.yxlbus.YxlBusNoParamNoResult;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class BaseSettingsActivity extends Activity implements ClickAction, HandlerAction {
    protected SettingDevInfoLayout llSettingDevInfoLayout;
    private static final String BUS_KEY_OBSERVE_RESET = "key_key_observe_reset";
    private Runnable runnable;
    private Stack<Integer> keyObserve;
    private List<Integer> keyOrder = Arrays.asList(KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_RIGHT,
            KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_DOWN,
            KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_UP);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_setting);
        initYxlBus();
        initView();
        initData();
    }

    private void initYxlBus() {
        YxlBusManager
                .getInstance()
                .addInterface(BUS_KEY_OBSERVE_RESET, new YxlBusNoParamNoResult() {
                    @Override
                    public void function() {
                        if (keyObserve.size() != keyOrder.size()) {
                            AppUtils.debugLog("恢复了按键监听");
                            //恢复健值监听
                            keyObserve.clear();
                            keyObserve.addAll(keyOrder);
                        }
                    }
                });

        runnable = () -> YxlBusManager.getInstance().invokeInterface(BUS_KEY_OBSERVE_RESET);
    }

    public void initView() {
        keyObserve = new Stack<>();
        keyObserve.addAll(keyOrder);

        llSettingDevInfoLayout = findViewById(R.id.llSettingDevInfoLayout);
        setOnClickListener(R.id.btnAppReset, R.id.btnUserReset);
    }

    public void initData() {
        llSettingDevInfoLayout.setItemText(R.id.cpu_model, CheckerUtils.getCpuInfo());
        llSettingDevInfoLayout.setItemText(R.id.cpu_parameters, CheckerUtils.getDeviceCPUCores() + " 核  " + CheckerUtils.getDeviceCpuCoresGHz() + " GHz");
        llSettingDevInfoLayout.setItemText(R.id.android_version, "Android" + Build.VERSION.RELEASE + " (" + Build.VERSION.SDK_INT + ")");
        llSettingDevInfoLayout.setItemText(R.id.model, Build.MODEL);
        llSettingDevInfoLayout.setItemText(R.id.brand, BimDataManager.getAppInfoInstance().getValue(AppInfo.BRAND));
        llSettingDevInfoLayout.setItemText(R.id.rom, BimTools.showROMInfo());
        llSettingDevInfoLayout.setItemText(R.id.ram, BimTools.showRAMInfo());
        llSettingDevInfoLayout.setItemText(R.id.app_version, BimDataManager.getAppInfoInstance().getValue(AppInfo.RZD_VERSION));

        llSettingDevInfoLayout.setItemText(R.id.stbId, BimDataManager.getAppInfoInstance().getValue(AppInfo.VIRTUAL_STBID));

        llSettingDevInfoLayout.setItemText(R.id.mac, BimDataManager.getAppInfoInstance().getValue(AppInfo.SOFT_VIRTUAL_MAC));
        llSettingDevInfoLayout.setItemText(R.id.ip, CheckerUtils.getLocalIpAddress());
        llSettingDevInfoLayout.setItemText(R.id.account, BimDataManager.getAppInfoInstance().getValue(AppInfo.ACCOUNT));
        llSettingDevInfoLayout.setItemText(R.id.province, BimDataManager.getAppInfoInstance().getValue(AppInfo.PROVINCE));

        ImageView ivStbIdBarCode = llSettingDevInfoLayout.findViewById(R.id.ivStbIdBarCode);
        ImageView ivInfoBarCode = findViewById(R.id.ivInfoBarCode);
        if (ivStbIdBarCode.getVisibility() == View.VISIBLE) {
            ivStbIdBarCode.setImageBitmap(getStbIdBarCodeBitmap());
        }
        if (ivInfoBarCode.getVisibility() == View.VISIBLE) {
            ivInfoBarCode.setImageBitmap(getInfoBarCodeBitmap());
        }
    }

    private Bitmap getStbIdBarCodeBitmap() {
        String stbId = BimDataManager.getAppInfoInstance().getValue(AppInfo.VIRTUAL_STBID);
        return BitmapUtil.generateBarBitmap(stbId, 800, 100);
    }

    private Bitmap getInfoBarCodeBitmap() {

        String contents = "";
        try {
            String brand = BimDataManager.getAppInfoInstance().getValue(AppInfo.BRAND);
            String model = Build.MODEL;
            String cpuModel = CheckerUtils.getCpuInfo();
            String cpuInfo = CheckerUtils.getDeviceCPUCores() +
                    URLEncoder.encode("核", "UTF-8") +
                    CheckerUtils.getDeviceCpuCoresGHz() + "GHz";
            String totalRam = BimTools.bytes2mb(BimTools.getTotalRAMMem());
            String totalRom = BimTools.bytes2mb(BimTools.getTotalROMMem());

            String mac = BimDataManager.getAppInfoInstance().getValue(AppInfo.VIRTUAL_MAC);
            String stbId = BimDataManager.getAppInfoInstance().getValue(AppInfo.VIRTUAL_STBID);
            String account = BimDataManager.getAppInfoInstance().getValue(AppInfo.ACCOUNT);
            String ip =  CheckerUtils.getLocalIpAddress();
            String app_version = BimDataManager.getAppInfoInstance().getValue(AppInfo.RZD_VERSION);
            String tvMac = MacUtils.getMac();
            String baseInfo = BimDataManager.getAppInfoInstance().getValue(AppInfo.BASE_INFO);
            //终端厂商
            String manufacturer = BimDataManager.getAppInfoInstance().getValue(AppInfo.MANUFACTURER);
            //终端型号
            String modelName = BimDataManager.getAppInfoInstance().getValue(AppInfo.MODEL_NAME);
            //一级平台授权码
            String appToken = BimDataManager.getAppInfoInstance().getValue(AppInfo.APP_TOKEN);
            contents = "https://softmbh.komect.com/reward/index.html?" +
                    "SDK=" + Build.VERSION.SDK_INT +
                    "&TVManufacturer=" + URLEncoder.encode(brand, "UTF-8") +
                    "&model=" + model +
                    "&cpu=" + cpuModel +
                    "&cpuInfo=" + cpuInfo +
                    "&systemTotalMemorySize=" + totalRam +
                    "&SDTotalSize=" + totalRom +
                    "&Manufacturer=" + manufacturer +
                    "&ModelName=" + modelName +
                    "&mac=" + mac +
                    "&STBID=" + stbId +
                    "&MobilePhoneNumber=" + account +
                    "&Account=" + account +
                    "&ip=" + ip +
                    "&version=" + app_version +
                    "&city=" + URLEncoder.encode("江苏省", "UTF-8") +
                    "&provinceCode=320000" +
                    "&tvmac=" + tvMac +
                    "&baseinfo=" + baseInfo +
                    "&appToken=" + appToken;
            contents = contents.replace(" ", "");
            AppUtils.debugLog("QR_code contents : " + contents);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        AppUtils.debugLog("Density : " + displayMetrics.density + ", densityDpi : " + displayMetrics.densityDpi +
                ", width : " + displayMetrics.widthPixels + ", height : " + displayMetrics.heightPixels);
        if (displayMetrics.densityDpi == 213) {
            //小米和海信电视的宽高设置为230时会很小，231会稍大，小于230一样效果，大于231一样效果
            return BitmapUtil.generateQRCode(contents, 231, 231);
        } else {
            return BitmapUtil.generateQRCode(contents, 300, 300);
        }
    }

    protected void setBtnEnAble(boolean enAble, @IdRes int... ids) {
        if (enAble) {
            for (int id : ids) {
                findViewById(id).setVisibility(View.VISIBLE);
            }
        } else {
            for (int id : ids) {
                findViewById(id).setVisibility(View.GONE);
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            int temp = keyObserve.peek();
            if (temp == event.getKeyCode()) {
                keyObserve.pop();
                if (keyObserve.size() == 0) {//用户全部按完了预定按键
                    //恢复健值监听
                    keyObserve.addAll(keyOrder);
                    removeCallbacks(runnable);
                    startActivity(new Intent(this, HiddenActivity.class));
                } else {
                    //做一个延时，延时两秒恢复按键状态
                    postDelayed(runnable, 5000);
                }
            } else if (keyObserve.size() != keyOrder.size()) {
                //恢复健值监听
                keyObserve.clear();
                keyObserve.addAll(keyOrder);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        YxlBusManager.getInstance().removeInterface(BUS_KEY_OBSERVE_RESET);
    }

}
